package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.RecommendUserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service // dubbo的
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findMaxScore(Long userId) {
        // 1.组装查询条件
        Query query = new Query(
                Criteria.where("toUserId").is(userId)  // 登录用户id
        ).with(Sort.by(Sort.Order.desc("score"))) // 缘分值降序
                .skip(0).limit(1);// 查询最高分
        // 2.查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        // 3.返回
        return recommendUser;
    }

    @Override
    public PageBeanVo findRecommendUserByPage(Integer pageNum, Integer pageSize, Long userId) {
        // 1.组装查询条件
        Query query = new Query(
                Criteria.where("toUserId").is(userId)  // 登录用户id
        ).with(Sort.by(Sort.Order.desc("score"))) // 缘分值降序
                .skip((pageNum - 1) * pageSize + 1).limit(pageSize);// 查询最高分

        // 2.查询list
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);

        // 3.查询count
        long count = mongoTemplate.count(query, RecommendUser.class);
        return new PageBeanVo(pageNum, pageSize, count, recommendUserList);
    }

    @Override
    public RecommendUser findByRecommendUserIdAndUserId(Long recommendUserId, Long userId) {
        // 1.组装查询条件
        Query query = new Query(
                Criteria.where("userId").is(recommendUserId) // 推荐用户id
                        .and("toUserId").is(userId) // 登录用户id
        );
        // 2.查询
        return mongoTemplate.findOne(query, RecommendUser.class);
    }
}
